package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.PreferenceUtils;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.linjian.togetherbirthday.utils.ThreadPoolManager;
import com.linjian.togetherbirthday.utils.UiUtils;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class CatalogueFragment extends Fragment implements View.OnClickListener {
    String className = this.getClass().getName();

    //listView1 的数据集合
    String mCatalogues1[];

    // 下拉容器
    private FrameLayout mDownMenu;
    // listView1
    private ListView item1;

    private View mView;
    private int mFoodpoition;
    private Item1Adatper mItem1Adatper;
    private long mItem1SelectedPosition = 0;

    String catalogues1[] = new String[]{"菜系", "火锅", "烤鱼", "烧烤", "咖啡厅", "粤菜馆", "浙菜", "人气餐厅", "打边炉/港式火锅", "本帮江浙菜", "快餐简餐", "自助餐", "日本菜湘菜", "西餐", "披萨", "四川火锅", "牛排", "东南亚菜"};


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        initView();
        return mDownMenu;
    }

    @Override
    public void onResume() {
        LoadDataAndSetListener();
        super.onResume();
    }

    private void initView() {
        mDownMenu = (FrameLayout) View.inflate(getActivity(), R.layout.down_menu_two, null);
        item1 = (ListView) mDownMenu.findViewById(R.id.item1);
        mView = mDownMenu.findViewById(R.id.bottom_view);
    }

    private void initListener() {
        mView.setOnClickListener(this);
        item1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Log.d("getChildCount", item1.getChildCount() + "");
//                Log.d("position", position + "");
                /**  用来保持 设置的itme信息**/
                /**---------------做个缓冲--------------------**/
                mItem1SelectedPosition = position;

                for (int i = 0; i < item1.getChildCount(); i++) {
                    //所有listview1 的item 字体颜色设置R.color.itemTextColor
                    ((TextView) (item1.getChildAt(i).findViewById(R.id.textview1))).setTextColor(getResources().getColor(R.color.itemTextColor));
                    //设置 listview1 的 item 未选中背景色 R.color.item1Color
                    item1.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.item1Color));
                }
                //选中条目设置 背景色和字体
                View view1 = mItem1Adatper.getView(position, view, parent);
                view1.setBackgroundColor(getResources().getColor(R.color.item2Color));
                //改变listview的数据

                checkListView2Close(mCatalogues1[(int) mItem1SelectedPosition]);
            }
        });

    }
    private class LoadDataTask implements Runnable{
        @Override
        public void run() {
            /**-------------网络请求数据--------------------**/
//            try {
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            mCatalogues1 = catalogues1;
            /**---------------模拟请求成功--------------------**/
            UiUtils.getMainHandler().post(new Runnable() {
                @Override
                public void run() {
                    Log.d("currentThread", Thread.currentThread() + "");
                    //模拟数据加载
                    initData();
                    initListener();
                }
            });
            /**-----------------------------------------------**/
        }
    }

    private void initData(){
        mItem1SelectedPosition = PreferenceUtils.getLong(getActivity(), className + "mItem1SelectedPosition", 0);

        mFoodpoition = 0;
        if (mItem1Adatper == null) {
            mItem1Adatper = new Item1Adatper();
        }

        item1.setAdapter(mItem1Adatper);
    }

    private void LoadDataAndSetListener() {
        //加载数据 开异步线程
        ThreadPoolManager.getLongPool().execute(new LoadDataTask());
    }
    /**--------------------------关闭监听      --------------------------------------**/
    public interface OnCloseListener{
        void close();
    }
    private OnCloseListener mOnCloseListener;
    public void setOnTouchOutSide2CloseListener(OnCloseListener onCloseListener){
        if (mOnCloseListener == null){
            mOnCloseListener = onCloseListener;
        }
    }
    //通知DownMenu处理关闭事件
    @Override
    public void onClick(View v) {
//        ((MainOneActivity)(getActivity())).closeDownMenu();


//        Log.d("mOnCloseListener != null", (mOnCloseListener != null) + "");
//        if (mOnCloseListener != null){
//            mOnCloseListener.close();
//        }
    }
    /**--------------------------------------------------------------------------------**/
    /**
     *请求地区商圈数据
     */
    private void regionStoreData(){
        HttpUtils.doGet(HttpContant.URL + HttpContant.CityBycoordinate
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("regionStoreData",response.body().string()));
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event){
        switch (event.getCls()){
            case "requestFail":
                TastyToast.makeText(getActivity(),"请求失败",TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                break;
            case "regionStoreData":
                Log.i("regionStoreData",event.getData().toString());
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    /**--------------------------回显监听      --------------------------------------**/
    public interface OnSetDataListener{
        void setData(String data1);
    }
    private OnSetDataListener mOnSetDataListener;
    public void setOnSetDataListener(OnSetDataListener onSetDataListener){
        if (mOnSetDataListener == null){
            mOnSetDataListener = onSetDataListener;
        }
    }
    protected void checkListView2Close(String superPosition){
        if (mOnSetDataListener != null){
            mOnSetDataListener.setData(superPosition);
        }
    }
    /**--------------------------------------------------------------------------------**/
    private class Item1Adatper extends BaseAdapter {
        @Override
        public int getCount() {
            return mCatalogues1.length;
        }

        @Override
        public Object getItem(int position) {
            return mCatalogues1[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            // TODO Auto-generated method stub
            Item1ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.sublist_item, null);
                viewHolder = new Item1ViewHolder();
                viewHolder.textView = (TextView) convertView
                        .findViewById(R.id.textview1);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (Item1ViewHolder) convertView.getTag();
            }
            viewHolder.textView.setText(mCatalogues1[position]);
            viewHolder.textView.setTextColor(getResources().getColor(R.color.itemTextColor));
            //因为数据没变化
            convertView.setBackgroundColor(getResources().getColor(R.color.item1Color));
            //

            if (position == mItem1SelectedPosition){
                viewHolder.textView.setTextColor(getResources().getColor(R.color.buttonSelectColor));
                convertView.setBackgroundColor(getResources().getColor(R.color.item2Color));
            }

            return convertView;
        }
    }


    public static class Item1ViewHolder {
        public TextView textView;
        public ImageView imageView;
        public LinearLayout layout;
    }

}
